//
//  LJNetworkManager.swift
//  LJWeibo
//
//  Created by 连俊杨 on 2017/10/12.
//  Copyright © 2017年 yang_ljun. All rights reserved.
//

import UIKit
import AFNetworking

enum LJHTTPMethod {
    case GET
    case POST
}

/// 网络管理工具
class LJNetworkManager: AFHTTPSessionManager {
    /// 管理工具单例
    static let sharedManager: LJNetworkManager = {
        let instance = LJNetworkManager()
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    /// 用户信息模型
    lazy var userAccount = LJUserAccount()
    
    
    /// 用户登录标记(计算型属性)
    var userLogin: Bool {
        return userAccount.access_token != nil
    }
    
    /// token访问 --- token的过期处理
    func tokenRequest(method: LJHTTPMethod = .GET, URLString: String, parameters: [String: String]?, completion: @escaping (_ json: Any?, _ isSuccess: Bool) -> ()) {
        
        guard let token = userAccount.access_token else {
            print("token失效，请重新登录")
            
            /// token失效，重新登录
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: UserShouldLoginNotification), object: self, userInfo: nil)
            
            completion(nil, false)
            return
        }
        
        /// 处理parameters
        var parameters = parameters
        if parameters == nil {
            parameters = [String: String]()
        }
        
        parameters?["access_token"] = token
        
        request(method: method, URLString: URLString, parameters: parameters, completion: completion)
    }
    
    
    /// 一个方法解决get/post 
    /// Request
    func request(method: LJHTTPMethod = .GET, URLString: String, parameters: [String: String]?, completion: @escaping (_ json: Any?, _ isSuccess: Bool) -> ()) {
        
        let success = { (task: URLSessionDataTask, json: Any?) -> () in
            completion(json, true)
        }
        
        let failure = { (task: URLSessionDataTask?, error: Error) -> () in
            print("数据加载错误\(error)")
            
            /// 处理task, token过期
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                
                /// 重新登录
                let userInfoDict = ["badCode": "badCode"]
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: UserShouldLoginNotification),
                    object: self,
                    userInfo: userInfoDict)
            }
            
            completion(nil, false)
        }
        
        if method == .GET {
            /// 成功就会调用到当面的success，失败就会调用到上面的failure，并且把相应数据传过去
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        else {
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
